package com.itestor.iptv.modules.common.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import com.itestor.iptv.modules.common.bean.AlertConfigBean;
import com.itestor.iptv.modules.common.bean.FileConfigBean;
import com.itestor.iptv.modules.common.bean.ProcessConfigBean;
import com.itestor.iptv.modules.common.bean.RecordModeConfigBean;
import com.itestor.iptv.modules.common.bean.SystemConfigBean;
import com.itestor.iptv.modules.common.bean.UploadConfigBean;
import com.itestor.iptv.utils.EthernetAdapter;
import com.itestor.iptv.utils.IpconfigUtil;
import com.itestor.iptv.utils.LocalCmdUtil;

/**
 * 
 * @author Mr.li
 * 
 */
public class RobotConfigService {

    /**
     * 
     */
    private Logger logger = Logger.getLogger(RobotConfigService.class);

    /**
     * 
     */
    public static String Itest_Captureconf_Token = "iTestCaptureConf";
    /**
     * 
     */
    public static String Itest_Importdata_Token = "importdata";
    /**
     * 
     */
    public static String Itest_Sconfig_Token = "sconfig";
    /**
     * 
     */
    public static String Itest_Serverinfo_Token = "serverinfo";

    /**
     * 
     */
    public static String Itest_UserConfig_Token = "userconfig";

    /**
     * 系统配置文件.
     */
    private Map<String, HierarchicalINIConfiguration> configurationMap = new HashMap<String, HierarchicalINIConfiguration>();

    /**
     * 进程服务映射
     */
    private Map<String, String> processServiceMap = new HashMap<String, String>();

    /**
     * 系统配置文件.
     */
    private Map<String, String> configFileMap = new HashMap<String, String>();

    /**
     * 初始化
     */
    public void init() {
        configurationMap.get(Itest_Captureconf_Token).setFileName(
                configFileMap.get(Itest_Captureconf_Token));
        configurationMap.get(Itest_Importdata_Token).setFileName(
                configFileMap.get(Itest_Importdata_Token));
        configurationMap.get(Itest_Sconfig_Token).setFileName(
                configFileMap.get(Itest_Importdata_Token));
        configurationMap.get(Itest_Serverinfo_Token).setFileName(
                configFileMap.get(Itest_Serverinfo_Token));

        try {
            configurationMap.get(Itest_Captureconf_Token).load();
            configurationMap.get(Itest_Importdata_Token).load();
            configurationMap.get(Itest_Sconfig_Token).load();
            configurationMap.get(Itest_Serverinfo_Token).load();

        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取系统配置
     * @return SystemConfigBean
     */
    public SystemConfigBean getSystemConfigBean() {
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Serverinfo_Token);

        try {
            configuration.load();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd",
                Locale.US);
        SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss",
                Locale.US);

        SystemConfigBean configBean = new SystemConfigBean();
        String systemTime = timeformat.format(new Date());
        configBean.setSystemTime(systemTime);
        String systemDate = dateformat.format(new Date());
        configBean.setSystemDate(systemDate);

        Map<String, EthernetAdapter> ethernetAdapterMap = IpconfigUtil
                .getEthernetAdapterMap();

        String macAddress = configuration.getString("serverinfo.macAddress");

        System.out.println("adapter size " + ethernetAdapterMap.size()
                + "macAddress : [" + macAddress + "]");

        EthernetAdapter adapter = ethernetAdapterMap.get(macAddress);

        if (null != adapter) {
            configBean.setHostIp(adapter.getIpAddress());
            configBean.setGateway(adapter.getGateway());
            configBean.setSubnetMask(adapter.getSubnetMask());
            configBean.setAdapterName(adapter.getAdapterName());
            configBean.setMacAddress(adapter.getPhysicalAddress());

            String ntpserver = LocalCmdUtil.execGetNtpServerCmd("/querysntp");
            configBean.setNtpServer(ntpserver);
        }

        return configBean;
    }

    /**
     * 获取告警配置
     * @return AlertConfigBean
     */
    public AlertConfigBean getAlertConfigBean() {
        AlertConfigBean bean = new AlertConfigBean();
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        try {
            configuration.load();
        } catch (ConfigurationException e) {            
            e.printStackTrace();
        }
        
        String moveDelay = configuration.getString("ItestCapture.movDelay");
        String warnVol = configuration.getString("ItestCapture.warnVol");
        String warnRtpLost = configuration
                .getString("ItestCapture.warnRtpLost");
        String warnRtpSe = configuration.getString("ItestCapture.warnRtpSe");
        String df = configuration.getString("ItestCapture.warnDf");
        String mlr = configuration.getString("ItestCapture.warnMlr");
        String warnBitRatio = configuration
                .getString("ItestCapture.warnBitratio");
        String warnVolTimes = configuration
                .getString("ItestCapture.warnVolTimes");
        String tcpRetran = configuration
        .getString("ItestCapture.tcpRetran");
        String tcpOrderErr = configuration
        .getString("ItestCapture.tcpOrderErr");
        
        bean.setMoveDelay(moveDelay);
        bean.setWarnVol(warnVol);
        bean.setWarnRtpLost(warnRtpLost);
        bean.setWarnRtpSe(warnRtpSe);
        bean.setDf(df);
        bean.setMlr(mlr);
        bean.setWarnBitRatio(warnBitRatio);
        bean.setWarnVolTimes(warnVolTimes);
        bean.setTcpRetran(tcpRetran);
        bean.setTcpOrderErr(tcpOrderErr);

        
        return bean;
    }

    /**
     * 获取文件配置
     * @return FileConfigBean
     */
    public FileConfigBean getFileConfigBean() {
        FileConfigBean bean = new FileConfigBean();
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);

        try {
            configuration.load();
        } catch (ConfigurationException e) {            
            e.printStackTrace();
        }
        
        
        String imageSavePath = configuration
                .getString("ItestCapture.imageSavePath");
        String videoSavePath = configuration
                .getString("ItestCapture.videoSavePath");
        String pcapSavePath = configuration
                .getString("ItestCapture.pcapSavePath");

        bean.setImageSavePath(imageSavePath);
        bean.setPcapSavePath(pcapSavePath);
        bean.setVideoSavePath(videoSavePath);

        return bean;
    }

    /**
     * 获取上传配置.
     * @return UploadConfigBean
     */
    public UploadConfigBean getUploadConfigBean() {
        UploadConfigBean bean = new UploadConfigBean();
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        
        try {
            configuration.load();
        } catch (ConfigurationException e) {            
            e.printStackTrace();
        }
        
        String isUpToDB = configuration.getString("ItestCapture.isUpToDB");
        String ipReportServerHost = configuration
                .getString("ItestCapture.ipReportServerHost");

        HierarchicalINIConfiguration importConf = configurationMap
                .get(Itest_Importdata_Token);
        String networkServerHost = importConf
                .getString("ImportData.robot_webhost");
        String dataBaseHost = importConf.getString("ImportData.database_host");

        bean.setDataBaseHost(dataBaseHost);
        bean.setIpReportServerHost(ipReportServerHost);
        bean.setIsUpToDB(isUpToDB);
        bean.setNetworkServerHost(networkServerHost);

        return bean;
    }

    /**
     * 获取记录模式.
     * @return RecordModeConfigBean.
     */
    public RecordModeConfigBean getRecordModeConfigBean() {
        RecordModeConfigBean bean = new RecordModeConfigBean();
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        try {
            configuration.load();
        } catch (ConfigurationException e) {            
            e.printStackTrace();
        }
        
        String movCapTime = configuration.getString("ItestCapture.movCapTime");
        String recordMode = configuration.getString("ItestCapture.recordMode");
        String capFormat = configuration.getString("ItestCapture.capFormat");
        String jpegQuality = configuration
                .getString("ItestCapture.jpegQuality");
        String videoQuanlity = configuration
                .getString("ItestCapture.videoQuanlity");
        String capInterval = configuration
                .getString("ItestCapture.capInterval");

        bean.setMovCapTime(movCapTime);
        bean.setRecordMode(recordMode);
        bean.setCapFormat(capFormat);
        bean.setJpegQuality(jpegQuality);
        bean.setVideoQuanlity(videoQuanlity);
        bean.setCapInterval(capInterval);

        return bean;
    }

    /**
     * 修改上传配置
     * @param uploadConfigBean
     * @throws ConfigurationException
     */
    public void modifyRobotUploadCfg(UploadConfigBean uploadConfigBean)
            throws ConfigurationException {

        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        
        configuration.setProperty("ItestCapture.isUpToDB", uploadConfigBean
                .getIsUpToDB());
        configuration.setProperty("ItestCapture.ipReportServerHost",
                uploadConfigBean.getIpReportServerHost());

        HierarchicalINIConfiguration importConf = configurationMap
                .get(Itest_Importdata_Token);
        importConf.setProperty("ImportData.robot_webhost", uploadConfigBean
                .getNetworkServerHost());
        importConf.setProperty("ImportData.database_host", uploadConfigBean
                .getDataBaseHost());

        try {
            configuration.save();
            importConf.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 修改告警配置
     * @param alertConfigBean
     * @throws ConfigurationException
     */
    public void modifyAlertConfigBean(AlertConfigBean alertConfigBean)
            throws ConfigurationException {
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        
        configuration.setProperty("ItestCapture.movDelay", alertConfigBean
                .getMoveDelay());
        configuration.setProperty("ItestCapture.warnVol", alertConfigBean
                .getWarnVol());
        configuration.setProperty("ItestCapture.warnRtpLost", alertConfigBean
                .getWarnRtpLost());
        configuration.setProperty("ItestCapture.warnRtpSe", alertConfigBean
                .getWarnRtpSe());
        configuration.setProperty("ItestCapture.warnDf", alertConfigBean
                .getDf());
        configuration.setProperty("ItestCapture.warnMlr", alertConfigBean
                .getMlr());
        configuration.setProperty("ItestCapture.warnBitratio", alertConfigBean
                .getWarnBitRatio());
        configuration.setProperty("ItestCapture.warnVolTimes", alertConfigBean
                .getWarnVolTimes());
        configuration.setProperty("ItestCapture.tcpRetran", alertConfigBean
                .getTcpRetran());
        configuration.setProperty("ItestCapture.tcpOrderErr", alertConfigBean
                .getTcpOrderErr());
        
        try {
            configuration.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 修改记录模式
     * @param recordModeConfigBean
     * @throws ConfigurationException
     */
    public void modifyRecordModeConfigBean(
            RecordModeConfigBean recordModeConfigBean)
            throws ConfigurationException {
        HierarchicalINIConfiguration configuration = configurationMap
                .get(Itest_Captureconf_Token);
        configuration.setProperty("ItestCapture.movCapTime",
                recordModeConfigBean.getMovCapTime());
        configuration.setProperty("ItestCapture.recordMode",
                recordModeConfigBean.getRecordMode());
        configuration.setProperty("ItestCapture.capFormat",
                recordModeConfigBean.getCapFormat());
        configuration.setProperty("ItestCapture.jpegQuality",
                recordModeConfigBean.getJpegQuality());
        configuration.setProperty("ItestCapture.videoQuanlity",
                recordModeConfigBean.getVideoQuanlity());
        configuration.setProperty("ItestCapture.capInterval",
                recordModeConfigBean.getCapInterval());

        try {
            configuration.save();
        } catch (ConfigurationException e) {
            logger.error(e.getMessage());
            throw e;
        }

    }

    /**
     * 获取进程配置信息
     * @return ProcessConfigBean
     */
    public ProcessConfigBean getProcessConfigInfo() {
        String irProcess = processServiceMap.get("irProcess");
        String qosProcess = processServiceMap.get("qosProcess");
        String qoeProcess = processServiceMap.get("qoeProcess");
        String ipProcess = processServiceMap.get("ipProcess");

        ProcessConfigBean bean = new ProcessConfigBean();
        bean.setIpReportStatus(LocalCmdUtil.execScCmd("query", ipProcess));
        bean.setIrStatus(LocalCmdUtil.execScCmd("query", irProcess));
        bean.setQoeStatus(LocalCmdUtil.execScCmd("query", qoeProcess));
        bean.setQosStatus(LocalCmdUtil.execScCmd("query", qosProcess));

        return bean;
    }

    /**
     * 修改进程状态
     * @param service
     * @param command
     * @return Integer
     */
    public Integer modifyRobotProcessState(String service, String command) {
        String local_service = processServiceMap.get(service);
        return LocalCmdUtil.execScCmd(command, local_service);
    }

    /**
     * 修改系统配置
     */
    public void modifySystemConfig(SystemConfigBean configBean) {
        String adapterName = configBean.getAdapterName();
        String subnetMask = configBean.getSubnetMask();
        String gateway = configBean.getGateway();
        String hostIp = configBean.getHostIp();
        String systemTime = configBean.getSystemTime();
        String systemDate = configBean.getSystemDate();

        String ntpSrever = configBean.getNtpServer();

        String[] timeCmdMsg = new String[] { systemDate, systemTime };
        LocalCmdUtil.execTimeCmd(timeCmdMsg);
        LocalCmdUtil.execNetshCmd(adapterName, hostIp, subnetMask, gateway);

        LocalCmdUtil.execNtpCmd("/setsntp", ntpSrever);

    }

    /**
     * 
     * @param pConfigurationMap
     */
    public void setConfigurationMap(
            Map<String, HierarchicalINIConfiguration> pConfigurationMap) {
        configurationMap = pConfigurationMap;
    }

    /**
     * 
     * @param pProcessServiceMap
     */
    public void setProcessServiceMap(Map<String, String> pProcessServiceMap) {
        processServiceMap = pProcessServiceMap;
    }

    /**
     * 
     * @param pConfigFileMap
     */
    public void setConfigFileMap(Map<String, String> pConfigFileMap) {
        configFileMap = pConfigFileMap;
    }

    /**
     * 
     * @return Map.
     */
    public Map<String, String> getSystemUser() {
        Map<String, String> userMap = null;
        Configuration config;
        try {
            config = new XMLConfiguration(configFileMap
                    .get(Itest_UserConfig_Token));
            String account = config.getString("account");
            String password = config.getString("password");

            if (null != account && null != password) {
                userMap = new HashMap<String, String>();
                userMap.put("account", account);
                userMap.put("password", password);
            }

        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return userMap;
    }

    /**
     * 
     * @param pUsername
     * @param pPassword
     * @return Map.
     */
    public Map<String, String> getLoginUser(String pUsername, String pPassword) {
        Map<String, String> userMap = null;
        Configuration config;
        
        try {
            config = new XMLConfiguration(configFileMap
                    .get(Itest_UserConfig_Token));
            String account = config.getString("account");
            String password = config.getString("password");

            if (null != account && null != password) {
                if (account.equals(pUsername) && password.equals(pPassword)) {
                    userMap = new HashMap<String, String>();
                    userMap.put("account", account);
                    userMap.put("password", password);
                }
            }

        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

        return userMap;
    }

    /**
     * 
     * @param pUsername
     * @param pPassword
     */
    public void modifyUserConfig(String pUsername, String pPassword) {

        XMLConfiguration config;
        try {
            config = new XMLConfiguration(configFileMap
                    .get(Itest_UserConfig_Token));            
            config.setProperty("account", pUsername);
            config.setProperty("password", pPassword);
            config.save();            
            
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

    }

}
